# -*- encoding: utf-8 -*-
import json
from .scores_spider import request_scores
from .result import result

def request_credit(uid,token):
    score_result = request_scores(uid,token)

    json_result = json.loads(score_result)

    if json_result.get('code') != 100:
      return score_result

    s_list = json_result.get('result')
    c_list = computGPA(uid,s_list)

    if len(c_list) == 0:
        return result(109)

    return result(100,c_list)

#计算学分总和跟学分绩点
def computGPA(uid,sList):

    score_list = []
    try:
        study_count = len(sList)
        fail_credits = 0.0

        for item in sList:
        	if item['score'] >= 60:
        		score_list.append(item)
        	else:
        		fail_credits += item['credit']

        scores = [s.get('score') for s in score_list]
        credits = [c.get('credit') for c in score_list]

        sum_c = 0.0 #学分的和
        sum_s_c = 0.0 #学分与成绩乘积的和

        for i in range(0,len(credits)):
        	sum_c += credits[i]
        	sum_s_c += credits[i]*scores[i]
        #已修学分总和，挂科学分总和，学分绩点保留两位小数,已修科数，挂科数
        return [{'passCredit':sum_c,'failedCredit':fail_credits,'gpa':round(sum_s_c/(10*sum_c),4)}]

    except Exception as e:
        print('parse credits error',e)
        return None

if __name__ == '__main__':
    data = request_credit('20135081','AQIC5wM2LY4Sfcxlobrfb8OgA1ZAaqhml9VI2OLOi5KXvCU%3D%40AAJTSQACMDE%3D%23')
    print(data)
